import { useEffect } from "react";
import { useModel } from "umi";
import OrgTree from "react-org-tree";
import { useReactive } from "ahooks";
import { Card as SemiCard, Button } from "@douyinfe/semi-ui";
import { IconRefresh } from "@douyinfe/semi-icons";
import { Spin, Space, Radio } from "antd";

import useGlobalSetting from "../hooks/globalSetting/useGlobalSetting";
import useStore from "../hooks/store/useStore";
import useAllStores from "../hooks/store/useAllStores";
import useStoreDepartmentToTree from "../hooks/store/useStoreDepartmentToTree";

import TreeOrganizationItem from "../components/tree/Organization";
import TreeStoreItem from "../components/tree/Store";
import TreeDepartmentItem from "../components/tree/Department";
import TreeCategoryItem from "../components/tree/Category";
import TreeControllerItem from "../components/tree/Controller";
import TreePersonItem from "../components/tree/Person";

// 概览
const DashboardPage = () => {
    const { windowInnerHeight, graphqlFetch, remoteData } = useModel("global");
    const { organizationInfo } = useModel("organization.info");
    const { applicationUuid } = useModel("application.info");

    const { loadGlobalSettings } = useGlobalSetting();
    const { loadAllStores } = useAllStores();
    const { loadStore } = useStore();
    const { loadStoreDepartmentsToTree } = useStoreDepartmentToTree();

    const state = useReactive({
        loading: false,
        allData: [],
        treeData: {},
        selectNode: null,
        isShowTree: false,
        horizontal: false,
    });

    useEffect(() => {
        state.treeData = {
            id: 0,
            oiUuid: organizationInfo.uuid,
            oiName: organizationInfo.fullName,
            type: "organization",
            children: [
                { id: 1, osUuid: "直营门店", osName: "直营门店", osType: "直营", type: "category" },
                { id: 2, osUuid: "合作门店", osName: "合作门店", osType: "店中店", type: "category" },
                // { id: 3, osUuid: "加盟门店", osName: "加盟门店", osType: "加盟", type: "store_type" },
            ],
        };
    }, []);

    const loadTreeData = async (isReload = false) => {
        state.loading = true;
        state.isShowTree = false;

        let cacheKey = window.organizationUuid + applicationUuid + "-globalSettings";

        if (isReload === false) {
            let cacheData = nodeCache.get(cacheKey);
            if (cacheData) {
                state.treeData = cacheData || {};
                state.loading = false;
                await sleep(500);
                state.isShowTree = true;
                return;
            }
        }

        let globalSettings = await loadGlobalSettings(true);

        let treeData = {
            id: 0,
            oiUuid: organizationInfo.uuid,
            oiName: organizationInfo.fullName,
            type: "organization",
            maInfo: globalSettings["organization-head"],
            children: [
                { id: 1, oiName: "直营门店", oiType: "直营门店", type: "category" },
                { id: 2, oiName: "合作门店", oiType: "合作门店", type: "category" },
                // { id: 3, osUuid: "加盟门店", osName: "加盟门店", osType: "加盟", type: "store_type" },
            ],
        };

        let directStores = await loadAllStores("直营门店");

        for (let i = 0; i < directStores.length; i++) {
            const item = directStores[i];
            let store = await loadStore(item.oiUuid);
            let departments = await loadStoreDepartmentsToTree({ oiType: "门店部门", oiRoot: store.oiUuid });
            let groups = await loadStoreDepartmentsToTree({ oiType: "门店班组", oiRoot: store.oiUuid });
            let children = store.children ? store.children.concat(departments.concat(groups)) : departments.concat(groups);
            directStores[i].children = children;
        }

        let cooperativeStores = await loadAllStores("合作门店");

        for (let i = 0; i < cooperativeStores.length; i++) {
            const item = cooperativeStores[i];
            let store = await loadStore(item.oiUuid);
            let departments = await loadStoreDepartmentsToTree({ oiType: "门店部门", oiRoot: store.oiUuid });
            let groups = await loadStoreDepartmentsToTree({ oiType: "门店班组", oiRoot: store.oiUuid });
            let children = store.children ? store.children.concat(departments.concat(groups)) : departments.concat(groups);
            cooperativeStores[i].children = children;
        }

        treeData.children[0].children = directStores;
        treeData.children[1].children = cooperativeStores;
        // // treeData.children[3].children = sData["加盟门店"];

        state.treeData = treeData;

        nodeCache.set(cacheKey, treeData, 2 * 60); // 缓存两分钟

        state.loading = false;
        state.isShowTree = true;
    };

    useEffect(() => {
        loadTreeData();
    }, []);

    const renderContent = (data) => {
        let content = "";
        switch (data.type) {
            case "organization":
                content = <TreeOrganizationItem key={data.id} data={data} selectNode={state.selectNode} />;
                break;
            case "category":
                content = <TreeCategoryItem key={data.id} data={data} selectNode={state.selectNode} />;
                break;
            case "person":
                content = <TreePersonItem key={data.id} data={data} selectNode={state.selectNode} />;
                break;
            case "store":
                content = <TreeStoreItem key={data.id} data={data} selectNode={state.selectNode} />;
                break;
            case "department":
                content = <TreeDepartmentItem key={data.id} data={data} selectNode={state.selectNode} />;
                break;
            case "controller":
                content = <TreeControllerItem key={data.id} data={data} selectNode={state.selectNode} />;
                break;
            default:
                break;
        }
        return content;
    };

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 48;

    return (
        <div style={{ padding: 10 }}>
            <SemiCard
                title={<span style={{ lineHeight: "32px", fontSize: 15 }}>门店总览</span>}
                headerStyle={{ padding: "7px 12px" }}
                headerExtraContent={
                    <Space>
                        <Radio.Group
                            options={[
                                { label: "横向", value: true },
                                { label: "竖向", value: false },
                            ]}
                            onChange={({ target: { value } }) => (state.horizontal = value)}
                            value={state.horizontal}
                            optionType="button"
                            buttonStyle="solid"
                        />
                        <Button icon={<IconRefresh />} onClick={() => loadTreeData(true)}></Button>
                    </Space>
                }
                shadows="always"
                bordered={false}
                bodyStyle={{ padding: 0, height: cardBodyHeight, overflow: "auto", textAlign: "center" }}
            >
                <Spin spinning={state.loading}>
                    {state.isShowTree && (
                        <OrgTree
                            horizontal={state.horizontal}
                            data={state.treeData}
                            collapsable={true}
                            labelClassName={"org-tree-label"}
                            expandAll={false}
                            renderContent={renderContent}
                            onClick={(e, data) => (state.selectNode = data)}
                        />
                    )}
                </Spin>
            </SemiCard>
        </div>
    );
};

export default DashboardPage;
